﻿<template>
  <div class="projectQa-container" style="height:auto">
    <el-card>
      <p style="text-align: center;font-size: 24pt;font-weight:bold">{{t("message.questionInfo.questionnairesurvey")}}</p>
      <p> &nbsp;</p>
      <!-- 使用 v-for 遍历问题列表，使用 index 作为 key -->
    <div v-for="(question, index) in state.questionlist" :key="question.qaIndex">
       <el-card>
        
    <label style="font-size:18pt;margin-top: 50px;font-size:14pt;font-weight:bold">{{ index + 1 }}.{{ question.qaContent }}</label>
          <p></p>
      <!-- 根据问题类型渲染不同的输入组件 -->
      <template v-if="question.qType === 'text'">
    
        <input type="text" style="width: 400px;height: 35px;font-size: 20px;" v-model="question.inputValues" placeholder="input content">
      </template>
      <template v-else-if="question.qType === 'number'">
 
        <input type="number" style="width: 400px;height: 35px;font-size: 20px;" v-model="question.inputValues" placeholder="input number">
      </template>
      <template v-else-if="question.qType === 'textarea'">
     
        <textarea  v-model="question.inputValues" placeholder="input more" style="width: 400px;height: 35px;font-size: 20px;"></textarea>
      </template>
           <template v-else-if="question.qType === 'select'">
        <select v-model="question.inputValues" style="width: 400px;height: 35px;font-size: 20px;" >
          <option v-for="(item, index) in dl(question.qTypeCode)" :key="item.value"  :value="item.label">
            {{ item.label }}
          </option>
        </select>
      </template>
      </el-card>
    </div>
     

      <template #footer>
        <div style="text-align: right;">
          <el-button @click="toback">{{ $t('message.pageConfiguration.cancel') }}</el-button>
          <el-button type="primary" @click="submit">{{ $t('message.pageConfiguration.save') }}</el-button>
          <el-button type="primary" @click="submitandsave">{{ $t('message.questionInfo.gensulotion') }}</el-button>

        </div>
      </template>
    </el-card>

    <Detail ref="DetailRef" />
  </div>
</template>

<script lang="ts" setup="" name="questionInfo">
import { onMounted, onUnmounted, reactive, ref, defineAsyncComponent, nextTick, watch,getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import editDialog from '/@/views/main/questionInfo/component/editDialog.vue'
import { getDictDataItem as di, getDictDataListToSelect as dl } from '/@/utils/dict-utils';
import Detail from '/@/views/main/projectResult/component/Detail.vue'
import {  getProResultDetail } from "/@/api/main/projectResult";
import { addQuestionInfo, updateQuestionInfo } from "/@/api/main/questionInfo";
import { PageQuestionInfo,GetProjectByCode,GetProjectByCodeByProjectNo, deleteQuestionInfo, batchDeleteQuestionInfo, importQuestionInfo, downLoadQuestionInfo } from '/@/api/main/questionInfo';
import { getAPI } from '/@/utils/axios-utils';
import { SysEnumApi } from '/@/api-services/api';
import commonFunction from '/@/utils/commonFunction';
import { auth } from '/@/utils/authFunction'
import { useI18n } from 'vue-i18n';
import { sum } from 'lodash-es';

import router from "/@/router"; 
import {useRoute} from "vue-router";

const opendetail = (row:any) => {
  console.log('detail',row)
  DetailRef.value?.openDialog(row);
};
const DetailRef = ref();
const { t, locale } = useI18n();
const { downFile } = commonFunction();
// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));

const uploaddialog = defineAsyncComponent(() => import('/@/components/table/uploaddialog.vue'));

const uploaddialogRef = ref();
const loading = ref();
const projectno = ref('');

// 页面加载时
onMounted(async () => {





  const route = useRoute(); 
// 检查 route 是否为 undefined
if (route) {
const projectNo = route? (route.query.ProjectNo as string) : undefined;
projectno.value=projectNo;
} else {
  console.error('无法获取路由信息');
}
var aaa = getData();

  console.log(aaa)
});
const tableRef = ref<RefType>();
const editDialogRef = ref();
const state = reactive({
  questionlist:[],
  editprojectQaTitle: '',
  selectlist: [{ key: '门店', value: '1' }, { key: '个人消费者', value: '2' }] as EmptyObjectType[],
  selectlist2: [{ key: '鞋', value: '1' }, { key: '服', value: '2' }, { key: '配', value: '3' }] as EmptyObjectType[],
  selectlist3: [{ key: '鞋子：41*34*15', value: '1' }, { key: '衣服：80*50*18', value: '2' }, { key: '配件：60*40*17', value: '3' }],
  selectlist4: [{ key: '配件：0.02-1.36KG', value: '1' }, { key: '衣服：0.3-1.6 KG', value: '2' }, { key: '鞋子：0.36-1.8KG', value: '3' }] as EmptyObjectType[],
  selectlist5: [{ key: '整箱：1000件', value: '1' }, { key: '零散1000件', value: '2' }] as EmptyObjectType[],
  selectlist6: [{ key: '整箱：19200件', value: '1' }, { key: '零拣：76800件', value: '2' }] as EmptyObjectType[],
  selectlist7: [{ key: '日常8H', value: '1' }, { key: '高峰20H（白夜班）', value: '2' }] as EmptyObjectType[],

  selectvalues2: "",
  selectvalues3: "",
  selectvalues4: "",
  selectvalues5: "",
  selectvalues6: "",
  selectvalues7: "",

  textarea1: "",
  textarea2: "",
  textarea3: "",
  textarea4: "",
  textarea5: "",
  editquestionInfoTitle: '',
  groupList: [] as Array<String>
  ,

		questions: [
											        {
                                QAIndex:0,
											          title: '仓库的尺寸？',
											          type: 'text',
													  Alias:'长',
											        },
													{
                              QAIndex:1,
													  title: '仓库的尺寸？',
													  type: 'text',
													  Alias:'宽',
													},
											        {
                                  QAIndex:2,
											          title: '仓库人员数量？',
											          type: 'text',
													  Alias:'人数',
											        },
											        {
                                  QAIndex:3,
											          title: '仓库面积？',
											          type: 'text',
													   Alias:'面积',
											        },
											        {
                                  QAIndex:4,
											          title: '业务类型？',
											          type: 'select',
											          options: ['类型 A', '类型 B']
											        },
											        {
                                  QAIndex:5,
											          title: '业务类型？',
											          type: 'select',
											          options: ['类型 A', '类型 B']
											        }
											      ],
			      answers: [],
				index: -1,
        inputform:{
          ProjectNo:"",
        },


});

const tb = reactive<TableDemoState>
  ({
    tableData: {

      // 表头内容（必传，注意格式）
      columns: [
        { prop: 'qACode', width: 130, label: t('message.questionInfo.qACode'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'qAName', width: 130, label: t('message.questionInfo.qAName'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'qAIndex', width: 130, label: t('message.questionInfo.qAIndex'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'qAContent', width: 130, label: t('message.questionInfo.qAContent'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'gField', width: 130, label: t('message.questionInfo.gField'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'inputValues', width: 130, label: t('message.questionInfo.inputValues'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'createUserName', width: 130, label: t('message.questionInfo.createUserName'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'updateUserName', width: 130, label: t('message.questionInfo.updateUserName'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'qType', width: 130, label: t('message.questionInfo.qType'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'qTypeCode', width: 130, label: t('message.questionInfo.qTypeCode'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'qAlias', width: 130, label: t('message.questionInfo.qAlias'), headerAlign: 'center', toolTip: true, sortable: 'custom', isCheck: true },
        { prop: 'action', width: 140, label: t('message.pageConfiguration.operate'), type: 'action', align: 'center', isCheck: true, fixed: 'right', hideCheck: true },
      ],
      // 配置项（必传）
      config: {
        isStripe: true, // 是否显示表格斑马纹
        isBorder: false, // 是否显示表格边框
        isSerialNo: false, // 是否显示表格序号
        isSelection: true, // 是否勾选表格多选
        showSelection: auth('questionInfo:batchDelete'), //是否显示表格多选
        pageSize: 20, // 每页条数
        hideExport: false, //是否隐藏导出按钮
        exportFileName: 'questionInfo', //导出报表的文件名，不填写取应用名称
      },
      // 搜索表单，动态生成（传空数组时，将不显示搜索，type有3种类型：input,date,select）
      search: [
        { label: t('message.questionInfo.qACode'), prop: 'qACode', placeholder: t('message.questionInfo.qACode'), required: false, type: 'input' },
        { label: t('message.questionInfo.qAName'), prop: 'qAName', placeholder: t('message.questionInfo.qAName'), required: false, type: 'input' },
        { label: t('message.questionInfo.qAContent'), prop: 'qAContent', placeholder: t('message.questionInfo.qAContent'), required: false, type: 'input' },
        { label: t('message.questionInfo.gField'), prop: 'gField', placeholder: t('message.questionInfo.gField'), required: false, type: 'input' },
        { label: t('message.questionInfo.inputValues'), prop: 'inputValues', placeholder: t('message.questionInfo.inputValues'), required: false, type: 'input' },
        { label: t('message.questionInfo.createUserName'), prop: 'createUserName', placeholder: t('message.questionInfo.createUserName'), required: false, type: 'input' },
        { label: t('message.questionInfo.updateUserName'), prop: 'updateUserName', placeholder: t('message.questionInfo.updateUserName'), required: false, type: 'input' },
        { label: t('message.questionInfo.qType'), prop: 'qType', placeholder: t('message.questionInfo.qType'), required: false, type: 'input' },
        { label: t('message.questionInfo.qTypeCode'), prop: 'qTypeCode', placeholder: t('message.questionInfo.qTypeCode'), required: false, type: 'input' },
        { label: t('message.questionInfo.qAlias'), prop: 'qAlias', placeholder: t('message.questionInfo.qAlias'), required: false, type: 'input' },
      ],
      param: {},
      defaultSort: {
        prop: 'createTime',
        order: 'ascending',
      },
    },
  });
// 监听语言切换
watch(locale, async () => {
  // 更新表头和搜索表单的国际化文本
  tb.tableData.columns.forEach(column => {
    switch (column.prop) {
      case 'id':
        column.label = t('message.questionInfo.id');
        break;
      case 'qACode':
        column.label = t('message.questionInfo.qACode');
        break;
      case 'qAName':
        column.label = t('message.questionInfo.qAName');
        break;
      case 'qAIndex':
        column.label = t('message.questionInfo.qAIndex');
        break;
      case 'qAContent':
        column.label = t('message.questionInfo.qAContent');
        break;
      case 'gField':
        column.label = t('message.questionInfo.gField');
        break;
      case 'inputValues':
        column.label = t('message.questionInfo.inputValues');
        break;
      case 'createUserName':
        column.label = t('message.questionInfo.createUserName');
        break;
      case 'updateUserName':
        column.label = t('message.questionInfo.updateUserName');
        break;
      case 'qType':
        column.label = t('message.questionInfo.qType');
        break;
      case 'qTypeCode':
        column.label = t('message.questionInfo.qTypeCode');
        break;
      case 'qAlias':
        column.label = t('message.questionInfo.qAlias');
        break;
      case 'action':
        column.label = t('message.pageConfiguration.operate');
        break;
    }
  });

  // 更新搜索表单的国际化文本
  tb.tableData.search.forEach(searchItem => {
    switch (searchItem.prop) {
      case 'id':
        searchItem.label = t('message.questionInfo.id');
        searchItem.placeholder = t('message.questionInfo.id');
        break;
      case 'qACode':
        searchItem.label = t('message.questionInfo.qACode');
        searchItem.placeholder = t('message.questionInfo.qACode');
        break;
      case 'qAName':
        searchItem.label = t('message.questionInfo.qAName');
        searchItem.placeholder = t('message.questionInfo.qAName');
        break;
      case 'qAIndex':
        searchItem.label = t('message.questionInfo.qAIndex');
        searchItem.placeholder = t('message.questionInfo.qAIndex');
        break;
      case 'qAContent':
        searchItem.label = t('message.questionInfo.qAContent');
        searchItem.placeholder = t('message.questionInfo.qAContent');
        break;
      case 'gField':
        searchItem.label = t('message.questionInfo.gField');
        searchItem.placeholder = t('message.questionInfo.gField');
        break;
      case 'inputValues':
        searchItem.label = t('message.questionInfo.inputValues');
        searchItem.placeholder = t('message.questionInfo.inputValues');
        break;
      case 'createUserName':
        searchItem.label = t('message.questionInfo.createUserName');
        searchItem.placeholder = t('message.questionInfo.createUserName');
        break;
      case 'updateUserName':
        searchItem.label = t('message.questionInfo.updateUserName');
        searchItem.placeholder = t('message.questionInfo.updateUserName');
        break;
      case 'qType':
        searchItem.label = t('message.questionInfo.qType');
        searchItem.placeholder = t('message.questionInfo.qType');
        break;
      case 'qTypeCode':
        searchItem.label = t('message.questionInfo.qTypeCode');
        searchItem.placeholder = t('message.questionInfo.qTypeCode');
        break;
      case 'qAlias':
        searchItem.label = t('message.questionInfo.qAlias');
        searchItem.placeholder = t('message.questionInfo.qAlias');
        break;
    }
  });

  // 等待下一次 DOM 更新循环完成后再进行表格刷新
  await nextTick();
  tableRef.value?.handleList(); // 刷新表格数据
});
// const getData = async (param: any) => {

//   loading.value = true;
//   var res = await GetProjectByCode(Object.assign(param));

//   loading.value = false;
//   state.questionlist=res.data.items;
//   console.log(res.data)
// };
const getData = async () => {

  loading.value = true;

console.log(projectno.value)


  state.inputform.ProjectNo=projectno.value;

var res = await GetProjectByCodeByProjectNo(state.inputform);
  state.inputform.ProjectNo=res.data.result[0].projectNo;
projectno.value = res.data.result[0].projectNo;
loading.value = false;
  state.questionlist=res.data.result;
  console.log('getpa',state.questionlist)
  state.answers = new Array(state.questionlist.length).fill('');
   state.questionlist.forEach((question, index) => {
      
            state.answers[index] = question.inputValues;
          
        });
  console.log(res.data)


  
};
const exportChangeData = (data: Array<EmptyObjectType>
) => {
  data.forEach((item) => {
    item.sysFlag = item.sysFlag == 1 ? t('message.questionInfo.yes') : t('message.questionInfo.no');
  });
  return data;
};
// 拖动显示列排序回调
const onSortHeader = (data: object[]) => {
  tb.tableData.columns = data;
};
// 搜索点击时表单回调
const onSearch = (data: EmptyObjectType) => {
  tb.tableData.param = Object.assign({}, tb.tableData.param, { ...data });
  nextTick(() => {
    tableRef.value.pageReset();
  });
};

const getGroupList = async () => {

};

//表格多选事件
const tableSelection = (data: EmptyObjectType[]) => {
  // console.log('表格多选事件', data)
  state.selectlist = data;
};

onMounted(async () => {
  getGroupList();
});

// 更新数据
const updateData = () => {
  tableRef.value.handleList();
  getGroupList();
};

// 打开新增页面
const openaddquestionInfo = () => {
  state.editquestionInfoTitle = t('message.questionInfo.addquestionInfo');
  editDialogRef.value?.openDialog({});
};

// 打开编辑页面
const openedit = (row: any) => {
  state.editquestionInfoTitle = t('message.questionInfo.editquestionInfo');
  editDialogRef.value?.openDialog(row);
};

// 删除
const delConfig = (row: any) => {
  ElMessageBox.confirm(t('message.messages.confirmDel') + `：【${row[tb.tableData.columns[1].prop.toString()]}】?`, t('message.messages.hint'), {
    confirmButtonText: t('message.messages.confirm'),
    cancelButtonText: t('message.messages.cancel'),
    type: 'warning',
  })
    .then(async () => {
      await deleteQuestionInfo({ id: row.id });
      tableRef.value.handleList();
      ElMessage.success(t('message.messages.deleteSuccess'));
    })
    .catch(() => { });
}; const toback=()=>
 {
   window.history.go(-1);
 }
  
const submit = async () => {


console.log(state.answers)

				  console.log(state.inputform.ProjectNo)
			 
  let values = { id: 0 };
  if (state.questionlist[0].id == undefined || state.questionlist[0].id == null || state.questionlist[0].id == "" || state.questionlist[0].id == 0) {
    //  const formData = state.questionlist.map((question, index) => ({
		// 			 ProjectNo:state.inputform.ProjectNo, 
		// 			 QACode:question.qaCode,
		// 			  QAName:question.qaName,
		// 			   GField: question.gField,
		// 			   NewDVaule:state.answers[index],
		// 		        QAIndex: index+1,
		// 		        QAContent: question.qaContent,
		// 		        InputValues: state.answers[index]
		// 		      }));


   var res =  await addQuestionInfo(state.questionlist);
   console.log(res)
     if(res.data.code==200)
     {
       getData();
        ElMessage.success("保存成功！");
     }
  } else {
    //  const formData = state.questionlist.map((question, index) => ({
    //        Id:question.id,
		// 			 ProjectNo:projectno.value, 
		// 			 QACode:question.qaCode,
		// 			  QAName:question.qaName,
		// 			   GField: question.gField,
		// 			   NewDVaule:state.answers[index],
		// 		        QAIndex: index+1,
		// 		        QAContent: question.qaContent,
		// 		        InputValues: state.answers[index]
		// 		      }));

   var res = await addQuestionInfo(state.questionlist);
     if(res.data.code==200)
     {
  getData();
        ElMessage.success("保存成功！");
     }
  }
};


const submitandsave = async () => {
  await submit();
  //state.questionlist[0]?.id=0;
  console.log(JSON.stringify(state.questionlist[0]))
  state.questionlist[0].projectNo=projectno.value;
  opendetail(state.questionlist[0]);
  //getProResultDetail(state.questionlist[0]);

  //save
}
//批量删除
const bacthDelete = () => {
  if (state.selectlist.length == 0) return false;
  ElMessageBox.confirm(t('message.messages.confirmBatchDel') + `【${state.selectlist[0].name}】${state.selectlist.length}` + t('message.messages.con'), t('message.messages.hint'), {
    confirmButtonText: t('message.messages.confirm'),
    cancelButtonText: t('message.messages.cancel'),
    type: 'warning',
  })
    .then(async () => {
      const ids = state.selectlist.map((item) => {
        return item.id;
      });
      var res = await batchDeleteQuestionInfo(ids);
      tableRef.value.pageReset();
      ElMessage.success(t('message.messages.deleteSuccess'));
    })
    .catch(() => { });



};
// 打开上传页面
const openUploadDialog = () => {
  uploaddialogRef.value.openUploadDialog();
};
const importData = async (param: any) => {
  var res = await importQuestionInfo(param);
  return res;
};

const downTemplete = async () => {
  var res = await downLoadQuestionInfo();
  downFile(res);
}     
</script>
<style scoped>

</style>